package com.tecnoagrosoft.zafra.control.activity.fragment;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


import org.json.JSONException;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tecnoagrosoft.zafra.control.activity.R;
import com.tecnoagrosoft.zafra.control.db.GenericManager;
import com.tecnoagrosoft.zafra.control.db.GestorDB;
import com.tecnoagrosoft.zafra.control.model.Weather;
import com.tecnoagrosoft.zafra.control.utils.JSONWeatherParser;
import com.tecnoagrosoft.zafra.control.utils.UtilsGeneric;
import com.tecnoagrosoft.zafra.control.utils.WeatherHttpClient;

public class ClimaFragment extends Fragment {

	View rootView;
	private EditText nuevaCiudad;
	private EditText nuevoPais;
	private GestorDB gestorDB;
	private GenericManager gM;
	private ImageButton btnNvoCity;
	private ImageView imgView;
	private ProgressDialog pDialog;
	private String ciudad = "Encarnacion";
	private String pais = "Py";
	private String city;
	private String lang;
	private TextView cityText;
	private TextView condDescr;
	private TextView temp;
	private TextView press;
	private TextView windSpeed;
	private TextView windDeg;
	private TextView sunrise;
	private TextView sunset;
	private TextView hum;
	private TextView date;

	private int id;
	private int idClimaBBDD;

	private static String sectorGeo;
	private static String Sunrise;
	private static String Sunset;
	private static int grado;

	final SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyy HH:mm:ss");
	Calendar cal = Calendar.getInstance();
	final Date today = cal.getTime();

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_clima, container, false);

		loadtable();

		return rootView;
	}

	private void loadtable() {

		this.setCity(ciudad + "," + pais);
		lang = "es";

		cityText = (TextView) rootView.findViewById(R.id.cityText);
		condDescr = (TextView) rootView.findViewById(R.id.condDescr);
		temp = (TextView) rootView.findViewById(R.id.temp);
		hum = (TextView) rootView.findViewById(R.id.hum);
		press = (TextView) rootView.findViewById(R.id.press);
		windSpeed = (TextView) rootView.findViewById(R.id.windSpeed);
		windDeg = (TextView) rootView.findViewById(R.id.windDeg);
		sunrise = (TextView) rootView.findViewById(R.id.sunrise);
		sunset = (TextView) rootView.findViewById(R.id.sunset);
		imgView = (ImageView) rootView.findViewById(R.id.condIcon);
		date = (TextView) rootView.findViewById(R.id.date);

		btnNvoCity = (ImageButton) rootView.findViewById(R.id.btnNvoCity);

		btnNvoCity = (ImageButton) rootView.findViewById(R.id.btnNvoCity);
		btnNvoCity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				dialogNuevaCiudad();

			}
		});

		try {

			idClimaBBDD = obtenerId();

			if (idClimaBBDD != 0) {
				try {
					climaBBDD();
				} catch (Exception e) {
					e.printStackTrace();
					try {
						finalize();
					} catch (Throwable f) {
						f.printStackTrace();
					}
				}
				if (UtilsGeneric.isConected(rootView.getContext())) {
					if (checkTime()) {
						conexion();
					} else {

						Toast.makeText(rootView.getContext(), getString(R.string.men_datos_ultimaConsulta), Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(rootView.getContext(), "           " + getString(R.string.men_error_conexion) + "\n" + getString(R.string.men_intentar_nuevamente),
							Toast.LENGTH_LONG).show();
					Toast.makeText(rootView.getContext(), getString(R.string.men_datos_ultimaConsulta), Toast.LENGTH_LONG).show();
				}
			} else {
				if (UtilsGeneric.isConected(rootView.getContext())) {
					conexion();
				} else {
					Toast.makeText(rootView.getContext(), getString(R.string.men_explication_necesita_conexion) + "='(", Toast.LENGTH_LONG).show();
					Toast.makeText(rootView.getContext(), getString(R.string.men_noDatos_BBDD), Toast.LENGTH_LONG).show();
					return;
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			;
		}

	}

	private boolean checkTime() {

		long restarFecha = 0L;
		long fechaActual = today.getTime();
		boolean result = false;

		String[] columns = { " _id, fecha_creacion" };

		gestorDB = new GestorDB(rootView.getContext());
		SQLiteDatabase db = gestorDB.getWritableDatabase();
		gM = new GenericManager(db);

		Cursor c = gM.getObjectById("clima", columns, idClimaBBDD);

		try {
			if (idClimaBBDD != 0) {
				Date fechaCreacion = (Date) df.parse(c.getString(c.getColumnIndex("fecha_creacion")));
				restarFecha = fechaActual - fechaCreacion.getTime();

				if (restarFecha >= 600000) {
					result = true;
				}
			}

		} catch (ParseException e) {
			e.printStackTrace();
			return result;
		}
		c.close();
		gM.close();
		db.close();
		gestorDB.close();
		return result;
	}

	private void climaBBDD() {

		String[] columns = { "city", "descripcion", "temp", "humidity", "pressure", "speed", "deg", "sunrise", "sunset", "condition_cod", "icon", "fecha_creacion" };

		gestorDB = new GestorDB(rootView.getContext());
		SQLiteDatabase db = gestorDB.getWritableDatabase();
		gM = new GenericManager(db);

		Cursor c = gM.getObjectById("clima", columns, idClimaBBDD);

		cityText.setText(c.getString(c.getColumnIndex("city")));
		condDescr.setText(c.getString(c.getColumnIndex("descripcion")).toUpperCase());
		temp.setText(c.getString(c.getColumnIndex("temp")));
		hum.setText(c.getString(c.getColumnIndex("humidity")));
		press.setText(c.getString(c.getColumnIndex("pressure")));
		windSpeed.setText(c.getString(c.getColumnIndex("speed")));
		windDeg.setText(c.getString(c.getColumnIndex("deg")));
		sunrise.setText(c.getString(c.getColumnIndex("sunrise")));
		sunset.setText(c.getString(c.getColumnIndex("sunset")));
		date.setText(c.getString(c.getColumnIndex("fecha_creacion")));

		int wId = c.getInt(c.getColumnIndex("condition_cod"));
		String idIcon = c.getString(c.getColumnIndex("icon"));

		loadIcon(wId, idIcon);

		c.close();
		gM.close();
		db.close();
		gestorDB.close();
	}

	private int obtenerId() {

		gestorDB = new GestorDB(rootView.getContext());
		SQLiteDatabase db = gestorDB.getReadableDatabase();
		String sqlBuscar = "Select MAX(_id) from clima";

		Cursor c = db.rawQuery(sqlBuscar, null);

		if (c.moveToFirst()) {

			Long idClima = c.getLong(0);
			id = Integer.parseInt(idClima.toString());

		}
		if (!c.isClosed()) {
			c.close();
			db.close();
			gestorDB.close();
		}
		return id;
	}

	private void conexion() throws IOException {

		try {

			JSONWeatherTask task = new JSONWeatherTask();
			task.execute(new String[] { this.getCity() });

			// JSONForecastWeatherTask task1 = new JSONForecastWeatherTask();
			// task1.execute(new String[] { this.getCity(), lang,
			// forecastDaysNum });

		} catch (Exception e) {
			Log.e("ERROR conexion", e.toString());
		}

	}

	private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {

		protected void onPreExecute() {

			pDialog = new ProgressDialog(rootView.getContext());
			pDialog.setMessage(getString(R.string.consultando));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Weather doInBackground(String... params) {
			Weather weather = new Weather();
			String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

			// Log.d("Data", data);

			if (data != null) {
				try {
					weather = JSONWeatherParser.getWeather(data);

				} catch (JSONException e) {
					Log.e("doInBackground", weather.toString());

				}
			} else {
				return null;
			}

			return weather;

		}

		@Override
		protected void onPostExecute(Weather weather) {
			super.onPostExecute(weather);

			if (weather != null) {

				pDialog.dismiss();

				Toast.makeText(rootView.getContext(), getString(R.string.men_explication_conexion_exitosa), Toast.LENGTH_LONG).show();

				int wId = weather.currentCondition.getWeatherId();
				String idIcon = weather.currentCondition.getIcon();

				loadIcon(wId, idIcon);

				gradoAsector(weather.wind.getDeg());
				Sunrise(weather.location.getSunrise());
				Sunset(weather.location.getSunset());

				cityText.setText(weather.location.getCity());
				condDescr.setText(weather.currentCondition.getDescr().toUpperCase());
				temp.setText("" + Math.round(weather.temperature.getTemp()));
				hum.setText("" + Math.round(weather.currentCondition.getHumidity()) + "%");
				press.setText("" + weather.currentCondition.getPressure() + " hPa");
				windSpeed.setText(Math.round(weather.wind.getSpeed() * 3600) / 1000 + " Km/h ");
				windDeg.setText("" + sectorGeo);
				sunrise.setText(Sunrise);
				sunset.setText(Sunset);
				date.setText(df.format(today));

				gestorDB = new GestorDB(rootView.getContext());
				SQLiteDatabase db = gestorDB.getWritableDatabase();
				gM = new GenericManager(db);

				ContentValues newClima = new ContentValues();
				newClima.put("lat", weather.location.getLatitude());
				newClima.put("lon", weather.location.getLatitude());
				newClima.put("country", weather.location.getCountry());
				newClima.put("city", cityText.getText().toString());
				newClima.put("sunrise", sunrise.getText().toString());
				newClima.put("sunset", sunset.getText().toString());
				newClima.put("descripcion", condDescr.getText().toString());
				newClima.put("condition_cod", weather.currentCondition.getWeatherId());
				newClima.put("icon", weather.currentCondition.getIcon());
				newClima.put("humidity", hum.getText().toString());
				newClima.put("pressure", press.getText().toString());
				newClima.put("temp_max", weather.temperature.getMaxTemp());
				newClima.put("temp_min", weather.temperature.getMinTemp());
				newClima.put("temp", temp.getText().toString());
				newClima.put("speed", windSpeed.getText().toString());
				newClima.put("deg", windDeg.getText().toString());
				newClima.put("fecha_creacion", df.format(today));
				newClima.put("activo", "true");

				gM.insertObject("clima", newClima);

				gM.close();
				db.close();
				gestorDB.close();
			} else {
				Toast.makeText(rootView.getContext(), getString(R.string.men_explication_error_establecer_conexion), Toast.LENGTH_LONG).show();
				pDialog.dismiss();
				return;
			}

		}

		private String Sunset(long sunset) {

			Date date = new Date(sunset * 1000L);
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT-3"));
			String formateDate = sdf.format(date);
			Sunset = formateDate;

			return Sunset;
		}

		private String Sunrise(long sunrise) {

			Date date = new Date(sunrise * 1000L);
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT-3"));
			String formateDate = sdf.format(date);
			Sunrise = formateDate;

			return Sunrise;

		}

	}

	// private class JSONForecastWeatherTask extends
	// AsyncTask<String, Void, WeatherForecast> {
	//
	// @Override
	// protected WeatherForecast doInBackground(String... params) {
	//
	// String data = ((new WeatherHttpClient()).getForecastWeatherData(
	// params[0], params[1], params[2]));
	// WeatherForecast forecast = new WeatherForecast();
	// try {
	//
	// forecast = JSONWeatherParser.getForecastWeather(data);
	//
	// } catch (JSONException e) {
	//
	// Log.e("JSONForecastWeatherTask", e.toString());
	// }
	// return forecast;
	//
	// }
	//
	// protected void onPostExecute(WeatherForecast forecastWeather) {
	// super.onPostExecute(forecastWeather);
	//
	// DailyForecastPageAdapter adapter = new DailyForecastPageAdapter(
	// Integer.parseInt(forecastDaysNum), getFragmentManager(),
	// forecastWeather);
	// pager.setAdapter(adapter);
	// }
	//
	// }

	private static String gradoAsector(float deg) {

		grado = (int) deg;
		if (grado >= 22.5 || grado <= 67.5) {
			sectorGeo = "Noreste (NE)";
		} else {
			if (grado >= 67.5 || grado <= 112.5) {
				sectorGeo = "Este (E)";
			} else {
				if (grado >= 112.5 || grado <= 157.5) {
					sectorGeo = "Sudeste (SE)";
				} else {
					if (grado >= 157.5 || grado <= 202.5) {
						sectorGeo = "Sur (S)";
					} else {
						if (grado >= 202.5 || grado <= 247.5) {
							sectorGeo = "Sudoeste (SO)";
						} else {
							if (grado >= 247.5 || grado <= 292.5) {
								sectorGeo = "Oeste (O)";
							} else {
								if (grado >= 292.5 || grado <= 337.5) {
									sectorGeo = "Noroeste (NO)";
								} else {
									if (grado <= 337.5 || grado >= 22.5) {
										sectorGeo = "Norte (N)";
									}
								}
							}
						}
					}
				}
			}
		}
		return sectorGeo;

	}

	private void dialogNuevaCiudad() {

		final Dialog dialog = new Dialog(rootView.getContext());
		dialog.setContentView(R.layout.fragment_nueva_ciudad);
		dialog.setTitle(R.string.title_dialog_nueva_ciudad);

		// Obtener los dasto

		nuevaCiudad = (EditText) dialog.findViewById(R.id.editTextNvaCiudad);
		nuevoPais = (EditText) dialog.findViewById(R.id.editTextNvoPais);

		dialog.show();

		// acceptar
		Button acceptarButton = (Button) dialog.findViewById(R.id.btn_acept);
		acceptarButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				ciudad = nuevaCiudad.getText().toString();
				pais = nuevoPais.getText().toString();

				setCity(ciudad + "," + pais);
				cityText.setText(ciudad);
				dialog.dismiss();
				try {
					conexion();
				} catch (IOException e) {

					e.printStackTrace();
				}

			}
		});
		// cancelar
		Button cancelarButton = (Button) dialog.findViewById(R.id.btn_cancel);
		cancelarButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close dialog
				dialog.cancel();
			}
		});

	}

	public static int getImage(int wId, String iconoId) {

		int n = 10;
		int result = 0;

		String codNoche = (String) iconoId.subSequence(2, 2);

		if (codNoche == "n") {
			wId = wId + n;
		}

		switch (wId) {

		// Thunderstorm
		case 200:
			result = R.drawable.storm;
			break;
		case 201:
			result = R.drawable.storm;
			break;
		case 202:
			result = R.drawable.storm;
			break;
		case 210:
			result = R.drawable.storm;
			break;
		case 211:
			result = R.drawable.storm;
			break;
		case 212:
			result = R.drawable.storm;
			break;
		case 221:
			result = R.drawable.storm;
			break;
		case 230:
			result = R.drawable.storm;
			break;
		case 231:
			result = R.drawable.storm;
			break;
		case 232:
			result = R.drawable.storm;
			break;

		// Drizzle
		case 300:
			result = R.drawable.showerrain;
			break;
		case 301:
			result = R.drawable.showerrain;
			break;
		case 302:
			result = R.drawable.showerrain;
			break;
		case 310:
			result = R.drawable.showerrain;
			break;
		case 311:
			result = R.drawable.showerrain;
			break;
		case 312:
			result = R.drawable.showerrain;
			break;
		case 313:
			result = R.drawable.showerrain;
			break;
		case 314:
			result = R.drawable.showerrain;
			break;
		case 321:
			result = R.drawable.showerrain;
			break;

		// Rain
		case 500:
			result = R.drawable.showersday;
			break;
		case 501:
			result = R.drawable.showersday;
			break;
		case 502:
			result = R.drawable.showersday;
			break;
		case 503:
			result = R.drawable.showersday;
			break;
		case 504:
			result = R.drawable.showersday;
			break;
		case 511:
			result = R.drawable.snow;
			break;
		case 520:
			result = R.drawable.stormnight;
			break;
		case 521:
			result = R.drawable.showerrain;
			break;
		case 522:
			result = R.drawable.showerrain;
			break;
		case 531:
			result = R.drawable.showerrain;
			break;

		// Snow
		case 600:
			result = R.drawable.snow;
			break;
		case 601:
			result = R.drawable.snow;
			break;
		case 602:
			result = R.drawable.snow;
			break;
		case 611:
			result = R.drawable.snow;
			break;
		case 612:
			result = R.drawable.snow;
			break;
		case 615:
			result = R.drawable.snow;
			break;
		case 616:
			result = R.drawable.snow;
			break;
		case 620:
			result = R.drawable.snow;
			break;
		case 621:
			result = R.drawable.snow;
			break;
		case 622:
			result = R.drawable.snow;
			break;

		// Clouds
		case 800:
			result = R.drawable.clear;
			break;
		case 810:
			result = R.drawable.clearnigh;
			break;
		case 801:
			result = R.drawable.fewcloud;
			break;
		case 811:
			result = R.drawable.fewcloudsnight;
			break;
		case 802:
			result = R.drawable.scatteredclouds;
			break;
		case 803:
			result = R.drawable.manyclouds;
			break;
		case 804:
			result = R.drawable.storm;
			break;
		}
		return result;
	}

	private void loadIcon(int wId, String idIcon) {

		imgView.setImageResource(getImage(wId, idIcon));

	}

}